package com.zktravel.service.message;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.odianyun.util.date.DateUtils;
import com.odianyun.util.date.TimeUtils;
import com.zktravel.model.dto.user.UserInfo;
import com.zktravel.model.vo.message.WxMsgExtTemplate;
import com.zktravel.model.vo.message.WxMsgPost;
import com.zktravel.model.vo.message.WxMsgTemplate;
import com.zktravel.service.user.UserService;
import com.zktravel.util.JsonHelper;

@Service
public class WxMsgServiceImpl implements WxMsgService {

    private static final Logger LOGGER = LoggerFactory.getLogger(WxMsgServiceImpl.class);

    @Resource
    private MessageSendService messageSendService;
    @Resource
    private UserService userService;

    //消息发送url
    private static final String MSG_PATH = "/wx/send-wx-message";

    //管理员openid
    public static final List<String> openIds = Lists.newArrayList(
            "oPKMy1tC6OcSXuPHT_pASqIqv2TE", // 何斌斌
            "oPKMy1j8mlbHCko-6Y5TKQAJe6-w", // 肖春生
            "oPKMy1nhr0_ofQINKsvyFI8ivE6o", // 张克祥
            "oPKMy1rUGKveKq4Xovx_747h1gGE" // 王克汗
    );


    //新订单管理员消息模板id
    public static final String TEMPLATE_ID_ORDER_ADMIN = "AC2wxB2PsDeHlV-Ux_nO93gEfIZXccETysVPyPXESN4";
    //    public static final String TEMPLATE_ID_ORDER_ADMIN = "towZTQBgqmeOqj4lydqOQ2cpSwFoyiCgQecCczM04gc";
    //新订单/购物车定制师消息模板id
    public static final String TEMPLATE_ID_ORDER_TAILOR = "AD9XmD8Z6NiDL-FRaIhHRd8VTNmsWkXGwSvHFL8YQ7M";

    //购物车定制师消息模板
    public static final String TEMPLATE_ID_CART_TAILOR = "AD9XmD8Z6NiDL-FRaIhHRd8VTNmsWkXGwSvHFL8YQ7M";
//    public static final String TEMPLATE_ID_ORDER_TAILOR = "FyoyEvcp2TbLWsAOvWMeVRoCG_c60XmQkesNhuYJmrk";

    //新订单管理员消息内容
    private String JSON_ORDER_ADMIN = "{\"first\":{\"value\":\"shopName,userName新下单\",\"color\":\"#353535\"},\"keyword1\":{\"value\":\"通知\",\"color\":\"#353535\"},\"keyword2\":{\"value\":\"mpName\",\"color\":\"#353535\"},\"remark\":{\"value\":\"¥totalAmt\",\"color\":\"#353535\"}}";
    //新订单定制师消息内容
    private String JSON_ORDER_TAILOR = "{\"first\":{\"value\":\"userName已下单：mpName\\n\",\"color\":\"#333333\"},\"keyword1\":{\"value\":\"currentDate\",\"color\":\"#666666\"},\"keyword2\":{\"value\":\"海淘商品\",\"color\":\"#666666\"},\"remark\":{\"value\":\"\n客人留言：remarkDesc\\n\\n尚未支付，请关注！\\n利润：¥totalAmt，签收后即可提现\\n查看客人订单 >>\",\"color\":\"#F94950\"}}";
    //加入购物车定制师消息内容
    private String JSON_CART_TAILOR = "{\"first\":{\"value\":\"userName已加购物车：mpName\\n\",\"color\":\"#333333\"},\"keyword1\":{\"value\":\"未下单\",\"color\":\"#666666\"},\"keyword2\":{\"value\":\"海淘商品\",\"color\":\"#666666\"},\"remark\":{\"value\":\"\\n尚未下单，请关注！\\n查看商品详情 >>\",\"color\":\"#F94950\"}}";

    private String JSON_MINIPROGRAM = "{\"appid\":\"wxdee0a34632fd34ee\",\"pagepath\":\"localpath\"}";

    /**
     * @param shopName 店铺名称
     * @param userName 用户昵称
     * @param mpName   所有商品名称逗号拼接的字符串超过30个字后续用...替换
     * @param totalAmt 参数说明
     * @return 返回类型
     * @throws
     * @Title: sendOrderMsgToAdmin
     * @Description: 新下单管理员消息
     * @author diaoxingguo
     * @date 2018年6月22日
     */
    @Override
    @Async("defaultExecutor")
    public void sendOrderMsgToAdmin(String shopName, String userName,
                                    String mpName, BigDecimal totalAmt) {

        WxMsgTemplate template = new WxMsgTemplate();
        template.setOpen_id(openIds);

        WxMsgPost post = this.handleWxMsgPost(TEMPLATE_ID_ORDER_ADMIN);
        Object data = this.handlNewOrderAdminData(shopName, userName, mpName, totalAmt);
        post.setData(data);
        template.setPost(post);

        //消息发送
        this.sendWxMsg(JsonHelper.bean2Json(template));
    }

    /**
     * @param shopName 店铺名
     * @param userId   C端用户id
     * @param mpName   商品名
     * @param totalAmt 总价
     * @return 返回类型
     * @throws
     * @Title: sendOrderMsgToAdminWithUserId
     * @Description: C端用户下单发消息给管理员
     * @author diaoxingguo
     * @date 2018年6月23日
     */
    @Override
    @Async("defaultExecutor")
    public void sendOrderMsgToAdminWithUserId(String shopName, Long userId,
                                              String mpName, BigDecimal totalAmt) {
        UserInfo userInfo = userService.getUserInfo(userId);
        String userName = userInfo.getCard().getName();
        this.sendOrderMsgToAdmin(shopName, userName, mpName, totalAmt);
    }

    /**
     * @param openIds   定制师wxopenid
     * @param userId    C端用户id
     * @param mpName    商品名
     * @param profitAmt 利润
     * @param orderId   订单id
     * @return 返回类型
     * @throws
     * @Title: sendOrderMsgToTailorWithUserId
     * @Description: C端用户下单发消息给定制师
     * @author diaoxingguo
     * @date 2018年6月23日
     */
    @Override
    @Async("defaultExecutor")
    public void sendOrderMsgToTailor(List<String> openIds,
                                     Long userId, String mpName, BigDecimal profitAmt, Long orderId, String remark) {
        UserInfo userInfo = userService.getUserInfo(userId);
        String userName = userInfo.getNickName(); // TODO 下单用户一般都是未认证用户 用nickname

        WxMsgExtTemplate template = new WxMsgExtTemplate();
        template.setOpen_id(openIds);

        WxMsgPost post = this.handleWxMsgPost(TEMPLATE_ID_ORDER_TAILOR);
        Object data = this.handleNewOrderTailorData(userName, mpName, profitAmt, remark);
        post.setData(data);
        String pagepath = "";
        try {
            pagepath = "entry/share.page?p=" + URLEncoder.encode("{\"path\":\"/app/tailor/order/shopOrderDetail.page\",\"params\":{\"id\":" + orderId.toString() + "}}", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("新下单定制师消息URLencode失败,openIds：{},userName:{},mpName:{},profitAmt:{},orderId:{}",
                    openIds, userName, mpName, profitAmt, orderId);
        }
        Object miniprogram = handleMiniprogram(orderId, pagepath);
        post.setMiniprogram(miniprogram);
        template.setPost(post);
        //消息发送
        this.sendWxMsg(JsonHelper.bean2Json(template));
    }

    /**
     * @param shopId 店铺id
     * @param userId 用户id
     * @param mpName 商品名
     * @param tpid   ta_product.id
     * @return 返回类型
     * @throws
     * @Title: sendCartMsgToTailor
     * @Description: 添加购物车发送消息给定制师
     * @author diaoxingguo
     * @date 2018年6月23日
     */
    @Override
    @Async("defaultExecutor")
    public void sendCartMsgToTailor(Long shopId, Long userId,
                                    String mpName, Long tpid) {
        //定制师信息
        UserInfo tailorInfo = userService.getUserInfoByShopId(shopId);
        //消费者信息
        UserInfo userInfo = userService.getUserInfo(userId);

        List<String> openIds = Lists.newArrayList(tailorInfo.getWxOpenId());
        String userName = userInfo.getCard().getName();

        WxMsgExtTemplate template = new WxMsgExtTemplate();
        template.setOpen_id(openIds);

        WxMsgPost post = this.handleWxMsgPost(TEMPLATE_ID_CART_TAILOR);
        Object data = this.handleCartTailorData(userName, mpName);
        post.setData(data);

        String pagepath = "";
        try {
            pagepath = "entry/share.page?p=" + URLEncoder.encode("{\"path\":\"/app/shop/client/detail/detail.page\",\"params\":{\"gid\":" + tpid.toString() + "}}", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("新下单定制师消息URLencode失败,openIds：{},userName:{},mpName:{},tpid:{}",
                    openIds, userName, mpName, tpid);
        }
        Object miniprogram = handleMiniprogram(tpid, pagepath);
        post.setMiniprogram(miniprogram);
        template.setPost(post);

        //消息发送
        this.sendWxMsg(JsonHelper.bean2Json(template));
    }


    //处理微信post内容
    private WxMsgPost handleWxMsgPost(String template_id) {
        WxMsgPost post = new WxMsgPost();
        post.setTouser("");
        post.setTemplate_id(template_id);
        post.setUrl("");
        post.setTopcolor("#000000");

        return post;
    }

    //处理新订单管理员消息内容
    private Object handlNewOrderAdminData(String shopName, String userName,
                                          String mpName, BigDecimal totalAmt) {
        String amt = "0";
        if (null != totalAmt) {
            amt = totalAmt.toString();
        }
        String msg = JSON_ORDER_ADMIN;
        msg = msg.replace("shopName", shopName).replace("userName", userName).replace("mpName", mpName).replace("totalAmt", amt);

        return JsonHelper.json2Bean(msg, Object.class);
    }

    //处理新订单定制师消息内容
    private Object handleNewOrderTailorData(String userName, String mpName,
                                            BigDecimal totalAmt, String remark) {
        String amt = "0";
        if (null != totalAmt) {
            amt = totalAmt.toString();
        }
        String msg = JSON_ORDER_TAILOR;
        String date = DateUtils.date2Str(new Date());
        msg = msg.replace("userName", userName).
                replace("mpName", mpName).
                replace("totalAmt", amt).
                replace("currentDate", date).
                replace("remarkDesc", null == remark ? "" : remark);
        return JsonHelper.json2Bean(msg, Object.class);
    }

    //处理新订单定制师消息内容
    private Object handleCartTailorData(String userName, String mpName) {
        String msg = JSON_CART_TAILOR;
        msg = msg.replace("userName", userName).replace("mpName", mpName);
        return JsonHelper.json2Bean(msg, Object.class);
    }

    //处理pagepath
    private Object handleMiniprogram(Long id, String pagepath) {
        pagepath = pagepath.replace("1000", id.toString());

        String msg = JSON_MINIPROGRAM;
        msg = msg.replace("localpath", pagepath);
        return JsonHelper.json2Bean(msg, Object.class);
    }

    //发送消息请求
    private void sendWxMsg(String jsonParams) {
        messageSendService.postRequest(MSG_PATH, jsonParams);
    }

}
